package com.whwace.web;

import com.whwace.core.BusinessContext;
import com.whwace.core.FlowToolsUtil;
import com.whwace.exception.AppException;
import com.whwace.utils.DatagramHandle;
import com.whwace.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@Slf4j
public class WebController {


    @GetMapping("/**")
    public ResponseEntity<Map> executeGet(HttpServletRequest request, HttpServletResponse response) {
        BusinessContext ctx = null;
        try {
            ctx = new BusinessContext(request, response);
            //请求报文处理
            DatagramHandle.checkRequestParams(ctx);
            FlowToolsUtil.doExecute(ctx);
            //请求报文处理
            DatagramHandle.checkResponseParams(ctx);
            return ResultUtil.ok(ctx);
        } catch (AppException e) {
            log.error("错误消息：",e.getMessage(),e);
            return ResultUtil.failure(ctx,e);
        } catch (Exception e){
            log.error("系统错误:",e);
            return ResultUtil.error(ctx,e);
        }
    }

    @PostMapping("/**")
    public ResponseEntity<Map> executePost(HttpServletRequest request, HttpServletResponse response) {
        BusinessContext ctx = null;
        try {
            ctx = new BusinessContext(request, response);
            //请求报文处理
            DatagramHandle.checkRequestParams(ctx);
            FlowToolsUtil.doExecute(ctx);
            //请求报文处理
            DatagramHandle.checkResponseParams(ctx);
            return ResultUtil.ok(ctx);
        } catch (AppException e) {
            log.error("错误消息：",e.getMessage(),e);
            return ResultUtil.failure(ctx,e);
        } catch (Exception e){
            log.error("系统错误:",e);
            return ResultUtil.error(ctx,e);
        }
    }
}
